<script>
import {
  TABLE_FIELD_QUARTER, TABLE_FIELD_YEAR,
} from '@/config'

/* IFTRUE_ONLY_NANCHANG
import { loadEnergyConsumptionStructure } from '@/api/enterpriseQuarterlyReport2'
FITRUE_ONLY_NANCHANG */
/* IFTRUE_NOT_NANCHANG */
import { loadEnergyConsumptionStructure } from '@/api/enterpriseQuarterlyReport'
/* FITRUE_NOT_NANCHANG */

import EnergyTableMixin from '@/components/quarterly-account-table-new/energy-table-mixin'
import ArrowSelectMixin from '@/components/quarterly-account-table-new/arrow-select-mixin'
import { selectEnergyDiscountList } from '@/api/energyDiscount'
import { uuid } from '@/utils'

import HeadEnergyConsumptionStructureTable from './head-energy-consumption-structure-table.vue'
import MixinYuanmeiQizhongxiang from './mixin-yuanmei-qizhongxiang'

const plus = (a, b) => {
  a = Number(a)
  b = Number(b)
  if (!a && !b) return ''
  a = a || 0;
  b = b || 0;
  const n = +(((+a) + (+b)).toFixed(4))
  return Number.isFinite(n) ? n : ''
}
export default {
  name: 'energy-consumption-structure-table',
  mixins: [EnergyTableMixin, ArrowSelectMixin, MixinYuanmeiQizhongxiang],
  components: {
    HeadEnergyConsumptionStructureTable
  },
  data () {
    return {
      // 表序号
      seriesNo: '表1-2',
      yuanmei_lists_acculate_columns: [
        'beginningInventory',
        'physicalQuantity',
        'amount',
        'industrialProduction',
        'forRawMaterials',
        'nonIndustrialProduction',
        'transportationConsumption',
        'endingInventory',
      ],
      yuanmei_lists_acculate_columns_all: [
        'beginningInventory',
        'physicalQuantity',
        'amount',
        'industrialProduction',
        'forRawMaterials',
        'nonIndustrialProduction',
        'transportationConsumption',
        'endingInventory',
        'useScalingFactor', // 采用折标系数
      ],

      // 计算保留到4位小数点
      precision: 4,

      // 标识是表1-2
      i_am_t_1_2: true,

      // 固定内容的列
      stableKeys: ['energyName', 'unitOfMeasurement', 'code', 'referenceDiscountFactor']
    }
  },
  computed: {
    // 消费量中的“合计"
    calc () {
      const lists = this.lists.map(v => v.data)
      return lists.map(
        vv => {
          const t1 = vv.find(x => x.key === 'industrialProduction')
          const t2 = vv.find(x => x.key === 'nonIndustrialProduction')
          return plus(t1 && t1.value, t2 && t2.value)
        }
      )
    },
    summary () {
      const obj = {
        energyName: '能源合计',
        unitOfMeasurement: '吨标准煤',
        code: '40',
        referenceDiscountFactor: '',
      }
      const precision = this.precision

      // 原煤子项里有输入则排除“原煤”
      const lists = this.lists.filter(v => {
        const data = v.data
        const isYuanmei = data.some(vv => (vv.key === 'energyName' && vv.value === '原煤') || (vv.key === 'code' && vv.value === '01'))
        return this.useQizhong ? !isYuanmei : true
      }).map(v => v.data)
      // 折标系数
      const sss = lists.map(v => {
        const target = v.find(vv => vv.key === 'useScalingFactor')
        return target ? target.value : ''
      })
      const props = this.flattenColumns.map(v => v.prop)
      const listsMap = props.reduce((acc, prop) => {
        if (!['referenceDiscountFactor', 'useScalingFactor'].includes(prop)) {
          acc[prop] = lists.map(v => {
            const target = v.find(vv => vv.key === prop)
            return target ? target.value : ''
          })
        }
        return acc
      }, {})
      // 消费量中的“合计"
      listsMap.total = [...this.calc]
      // ①期初库存合计=能源品种×采用折标系数（累加）；
      // ②实物量合计=上列数值累加；
      // ③金额合计=上列数值累加；
      // ④消费量：工业生产消费、用于原材料、非工业生产消费、合计中运输工具消费分别=能源品种×采用折标系数（累加）
      // 合计=工业生产消费累加值+非工业生产消费累计值；
      // ⑤期末库存合计=能源品种×采用折标系数（累加）。
      const accumulate = (prop, withFactor) => {
        const n = +(listsMap[prop].reduce((acc, v, i) => {
          const f = this.is_empty_value(sss[i]) ? 1 : sss[i]
          acc += (Number.isFinite(+v) ? +v : 0) * (withFactor ? (+f) : 1)
          return acc
        }, 0).toFixed(precision))
        return Number.isFinite(n) ? n : ''
      }
      const getValue = (prop) => {
        if (
          [
            // 'beginningInventory', 'endingInventory',
            'industrialProduction',
            'forRawMaterials',
            'nonIndustrialProduction',
            'transportationConsumption',
            'physicalQuantity',
          ].includes(prop)
        ) {
          // 期初库存量、期末库存合计
          // 工业生产消费、用于原材料、非工业生产消费、合计中运输工具消费
          return accumulate(prop, true)
        } else if (
          ['amount'].includes(prop)
        ) {
          // 金额,钱保留2位小数
          return accumulate(prop).toFixed(2)
        } else if (
          prop === 'total'
        ) {
          return plus(
            getValue('industrialProduction'),
            getValue('nonIndustrialProduction')
          )
        }
      }
      const data = this.flattenColumns.map(v => {
        let editable = true
        if (
          Object.keys(obj).includes(v.prop)
        ) {
          editable = false
        }
        const value = obj[v.prop] || getValue(v.prop);
        return {
          key: v.prop,
          value: (Number(value) && v.prop !== 'code') ? Number(value).toFixed(v.prop === 'amount' ? 2 : precision) : value,
          editable,
        }
      })

      return {
        uuid: uuid(),
        data: data
      }
    },
    errorsKeys () {
      return [
        'beginningInventory',
        'physicalQuantity',
        'endingInventory',
      ]
    },
    forRawMaterialsErrors () {
      // 工业生产消费≥用于原材料
      return this.lists.reduce((acc, v, i) => {
        const data = v.data
        const a = (data.find(vv => vv.key === 'forRawMaterials') || {}).value;
        const b = (data.find(vv => vv.key === 'industrialProduction') || {}).value;
        acc[i] = (Number(a) || Number(b)) && Number(a) > Number(b)
        return acc
      }, {})
    },
    transportationConsumptionErrors () {
      // 消费合计≥运输工具消费
      const calc = this.calc
      return this.lists.reduce((acc, v, i) => {
        const data = v.data
        const a = (data.find(vv => vv.key === 'transportationConsumption') || {}).value;
        acc[i] = (Number(a) || Number(calc[i])) && Number(calc[i]) < Number(a)
        return acc
      }, {})
    },
    errors () {
      return this.lists.reduce((acc, v, i) => {
        const data = v.data;
        // const code = (data.find(vv => vv.key === 'code') || {}).value;
        const a1 = (data.find(vv => vv.key === 'beginningInventory') || {}).value;
        const a2 = (data.find(vv => vv.key === 'physicalQuantity') || {}).value;

        const t1 = data.find(x => x.key === 'industrialProduction');
        const t2 = data.find(x => x.key === 'nonIndustrialProduction');

        const b2 = (data.find(vv => vv.key === 'endingInventory') || {}).value;

        const s = plus(t1 && t1.value, t2 && t2.value)

        // 期初库存量+购进量  =  消费量合计+期末库存
        acc[i] = !((Number(a1) + Number(a2)).toFixed(6) === (Number(s) + Number(b2)).toFixed(6));
        return acc;
      }, {});
    },
    hasError () {
      return Object.values(this.errors).some(v => v) ||
        Object.values(this.forRawMaterialsErrors).some(v => v) ||
        Object.values(this.transportationConsumptionErrors).some(v => v)
    }
  },
  created () {
    this.loadList = loadEnergyConsumptionStructure
  },
  methods: {
    getEnergyDiscount () {
      return selectEnergyDiscountList().then(res => {
        return res.data || []
      })
    },
    transfer (lists) {
      const props = this.flattenColumns.map(v => v.prop)
      const stableKeys = this.stableKeys || [];
      return lists.map(v => {
        return {
          uuid: uuid(),
          informant: {
            personInCharge: v.personInCharge,
            informer: v.informer,
            telephone: v.telephone,
            fillInDate: v.fillInDate,
          },
          data: props.map(vv => {
            const editable = !['energyName', 'unitOfMeasurement', 'code', 'total', 'referenceDiscountFactor'].includes(vv)
            return {
              key: vv,
              value: String(!this.is_empty_value(v[vv]) ? v[vv] : ''),
              editable,
              stable: stableKeys.includes(vv),
              calculable: vv === 'total'
            }
          })
        }
      })
    },
    getCalc (row, prop, value) {
      const calc = this.calc
      if (prop === 'total') {
        return calc[row]
      }
      return value
    },
    // 初始化表数据
    initLists (params, loadOnClickPrevButton, needInformant = true) {
      // 查询企业填报的数据
      if (this.loadList) {
        params = params || {
          [TABLE_FIELD_YEAR]: this.year,
          [TABLE_FIELD_QUARTER]: this.quarter,
          tenantId: this.enterpriseId
        }
        return this.loadList({
          ...params,
          loadOnClickPrevButton,
        }).then(async res => {
          if (res.code === 200) {
            let data = res.data || []
            if (data.length === 0) {
              // 为空时加载默认能源名称
              const energyDiscount = await this.getEnergyDiscount()
              data = energyDiscount.map(
                /**
                 *
                 * @param v{{
                 *  id: string | number;
                 *  name: string;
                 *  discountFactorUnit: string;
                 *  referenceCoefficient: string;
                 * }}
                 * @returns {{unitOfMeasurement: (*|string), referenceDiscountFactor: (*|string), code: string, useScalingFactor: number, energyName: string}}
                 */
                v => ({
                  energyName: v.name || '',
                  unitOfMeasurement: v.discountFactorUnit ? (v.discountFactorUnit.split('/')[1]) : '吨标准煤',
                  useScalingFactor: Math.min(
                    ...(v.referenceCoefficient || '').split('-').map(vv => +vv)
                  ),
                  referenceDiscountFactor: v.referenceCoefficient || '',
                  code: String(v.id).padStart(2, '0'),
                })
              )
            } else {
              const findIndex = data.findIndex(v => v.energyName === '能源合计' || v.code === '40')
              if (findIndex > -1) {
                data.splice(findIndex, 1)
              }
            }

            // 原煤初始采用折标系数
            for (const v of data) {
              if (v.code === '01') {
                this.origin_user_yuanmei_factor = v.useScalingFactor;
                break;
              }
            }

            this.isKept = !needInformant;
            this.lists = this.transfer(data)

            this.$nextTick(() => {
              this.initInputIndex()
            })
          }
        }).catch(() => {
          console.log('reject')
          this.$nextTick(() => {
            this.initInputIndex()
          })
        })
      }
    },
  },
}
</script>

<template>
  <div class="bg-white height-100 quarterly-account-table position-relative overflow-hidden">
    <slot name="title" :title="title" :series-no="seriesNo">
      <h2 class="table-title">
        {{title}}
      </h2>
    </slot>
    <div class="report-table-head">
      <HeadEnergyConsumptionStructureTable :show-line-number="showLineNumber"></HeadEnergyConsumptionStructureTable>
    </div>
    <el-scrollbar :style="{height: 'calc(100% - 186px)'}" wrap-style="overflow-x: hidden;">
      <table class="report-table" :class="{'is-readonly-table': readonly}">
        <tbody ref="tbody">
        <tr v-for="(item, i) in lists" :key="item.uuid">
          <th v-if="showLineNumber" class="is-stable-cell width-40px line-number">{{i + 1}}</th>
          <td
            v-for="(d, index) in item.data" :key="item.uuid + index"
            :class="{
              'is-stable-cell': d.stable,
              'is-computed-cell': d.calculable || d._computed,
              'is-editable-cell': d.editable && !readonly
            }"
            :style="{
              textAlign: index === 0 ? 'left' : 'center',
              width: index === 0 ? '160px' : 'auto'
            }"
          >
            <div v-if="!d.editable || readonly" class="span-cell inline-flex">
              <div style="width: 55px;text-align:right;" v-if="prefixBlankWithQizhong(d.value)">{{ prefixBlankWithQizhong(d.value) }}</div>
              {{d.calculable ? calc[i] : d.value}}
            </div>
            <div v-else-if="errorsKeys.includes(d.key)" class="input-cell" :class="{ 'is-error': (errors[i])}">
              <el-tooltip :disabled="!errors[i]" content="期初库存量+购进量=消费量合计+期末库存" placement="top">
                <input type="text" v-model="d.value" v-only-positive-number="val => d.value = val" @click="clickHandler($event, i)">
              </el-tooltip>
            </div>
            <div v-else-if="'forRawMaterials' === (d.key)" class="input-cell" :class="{ 'is-error': (forRawMaterialsErrors[i])}">
              <el-tooltip :disabled="!forRawMaterialsErrors[i]" content="工业生产消费≥用于原材料" placement="top">
                <input type="text" v-model="d.value" v-only-positive-number="val => d.value = val" @click="clickHandler($event, i)">
              </el-tooltip>
            </div>
            <div v-else-if="'transportationConsumption' === (d.key)" class="input-cell" :class="{ 'is-error': (transportationConsumptionErrors[i])}">
              <el-tooltip :disabled="!transportationConsumptionErrors[i]" content="消费合计≥运输工具消费" placement="top">
                <input type="text" v-model="d.value" v-only-positive-number="val => d.value = val" @click="clickHandler($event, i)">
              </el-tooltip>
            </div>
            <div v-else class="input-cell">
              <input type="text" v-model="d.value" v-only-positive-number="val => d.value = val" @click="clickHandler($event, i)">
            </div>
          </td>
        </tr>
        <tr>
          <th v-if="showLineNumber" class="is-stable-cell width-40px line-number">{{lists.length + 1}}</th>
          <td v-for="(item, index) in summary.data" :key="summary.uuid + index"
            :style="{
              textAlign: index === 0 ? 'left' : 'center',
              width: index === 0 ? '160px' : 'auto'
            }"
            :class="{
              'is-stable-cell': stableKeys.includes(item.key),
              'is-computed-cell': !stableKeys.includes(item.key),
            }"
          >
            <div class="span-cell">
              {{item.value}}
            </div>
          </td>
        </tr>
        </tbody>
      </table>
      <report-person ref="reportPerson" :is-kept="isKept" :informer="informant" :readonly="readonly"></report-person>
      <div v-if="tableDescription" class="fill-description">
        <template>
          <!-- <p>说明：</p>
          <p>1．主要逻辑审核关系：</p>
          <p class="padding-horizontal">(1) 消费合计=工业生产消费+非工业生产消费。</p>
          <p class="padding-horizontal">(2) 工业生产消费≥用于原材料。</p>
          <p class="padding-horizontal">(3) 消费合计≥运输工具消费。</p>
          <p>2．企业只填写本企业消耗的有关能源品种数值。如本表未包括企业消耗的能源品种，企业应根据统计部门要求归并入相应能源品种内。</p>
          <p>3．能源合计=∑某种能源×某种能源折标准煤系数（不重复计算“其中”项）。</p>
          <p>4．综合能源消费量的计算方法：</p>
          <p class="padding-horizontal">(1)非能源加工转换企业：综合能源消费量=工业生产消费的能源折标量合计-回收利用折标量合计（表1-2-1中第13列）。</p>
          <p class="padding-horizontal">(2)能源加工转换企业：综合能源消费量=工业生产消费的能源折标量合计-能源加工转换产出折标量合计（表1-2-1中第12列）-回收利用折标量合计（表1-2-1中第13列）。</p> -->
        </template>

        <el-input type="textarea" class="width-100 table-description" :value="tableDescription" readonly autosize></el-input>
      </div>
    </el-scrollbar>
  </div>
</template>
